/*******************************************************************************
 * Package: com.hngtrust.iir.company.service.impl
 * Type:    BailoutServiceImpl
 * Date:    2021-5-25 17:11
 *
 * Copyright (c) 2021 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.hngtrust.iir.company.service.impl;

import com.hngtrust.framework.page.PageResult;
import com.hngtrust.framework.page.service.PageService;
import com.hngtrust.iir.base.entity.Dict;
import com.hngtrust.iir.base.service.DictService;
import com.hngtrust.iir.company.controller.vo.ListBondFinanceRespVO;
import com.hngtrust.iir.company.controller.vo.ListDebitCreditRespVO;
import com.hngtrust.iir.company.controller.vo.ListGuaranteeRespVO;
import com.hngtrust.iir.company.controller.vo.ListHolderReqVO;
import com.hngtrust.iir.company.dto.ListFinanceRespDTO;
import com.hngtrust.iir.company.entity.CompBondFinance;
import com.hngtrust.iir.company.entity.CompDebitCredit;
import com.hngtrust.iir.company.entity.CompGuarantee;
import com.hngtrust.iir.company.service.BailoutService;
import com.hngtrust.iir.company.service.CompBondFinanceService;
import com.hngtrust.iir.company.service.CompDebitCreditService;
import com.hngtrust.iir.company.service.CompGuaranteeService;
import com.hngtrust.iir.constant.Constant;
import com.hngtrust.iir.dto.ReqDTO;
import com.hngtrust.iir.util.DateUtils;
import com.hngtrust.iir.util.ListUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 公司融资信息
 *
 * @author Chentianyong
 * @date 2021-5-25 17:11
 */

@Service
public class BailoutServiceImpl implements BailoutService {
    @Autowired
    private CompBondFinanceService compBondFinanceService;
    
    @Autowired
    private CompDebitCreditService compDebitCreditService;
    
    @Autowired
    private CompGuaranteeService compGuaranteeService;
    
    
    @Autowired
    private DictService dictService;
    
    /**
     * 分页服务
     */
    @Autowired
    private PageService pageService;
    
    @Override
    public ListFinanceRespDTO listFinance(ListHolderReqVO req) {
        CompBondFinance compBond = new CompBondFinance();
        BeanUtils.copyProperties(req,compBond);
        List<ListFinanceRespDTO.FinanceCash> list = compBondFinanceService.queryFinance(compBond);
    
        ListFinanceRespDTO resp = new ListFinanceRespDTO();
        Integer cnt = 0;
        BigDecimal totalAmount = BigDecimal.valueOf(0);
        BigDecimal baseAll = BigDecimal.valueOf(0);
        BigDecimal base = BigDecimal.valueOf(0);
        String year = null;
        List<ListFinanceRespDTO.FinanceCash> cashList = new ArrayList<>();
        List<ListFinanceRespDTO.FinanceCost> costList = new ArrayList<>();
        //重新组装数据
        //处理最近5年
        Boolean year1 = false;
        Boolean year2 = false;
        Boolean year3 = false;
        Boolean year4 = false;
        Boolean year5 = false;
        for(ListFinanceRespDTO.FinanceCash cash : list){
            if(null == year){
                year = cash.getYear();
            }
            if(cash.getYear().compareTo(String.valueOf(DateUtils.getYear(new Date()))) == 0){
                year1 = true;
            }
            if(cash.getYear().compareTo(String.valueOf(DateUtils.getYear(new Date()) - 1)) == 0){
                year2 = true;
            }
            if(cash.getYear().compareTo(String.valueOf(DateUtils.getYear(new Date()) - 2)) == 0){
                year3 = true;
            }
            if(cash.getYear().compareTo(String.valueOf(DateUtils.getYear(new Date()) - 3)) == 0){
                year4 = true;
            }
            if(cash.getYear().compareTo(String.valueOf(DateUtils.getYear(new Date()) - 4)) == 0){
                year5 = true;
            }
            if(year.compareTo(cash.getYear()) != 0){
                for(ListFinanceRespDTO.FinanceCash obj : cashList){
                    if(obj.getYear().compareTo(year) == 0 && totalAmount.compareTo(BigDecimal.valueOf(0)) > 0 && null != obj.getFinancingAmount()){
                        obj.setTotalAmount(totalAmount);
                        obj.setRate(obj.getFinancingAmount().divide(totalAmount, Constant.RETAIN_DECIMAL_DIGIT_SIX, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                    }
                }
                //处理融资成本率
                ListFinanceRespDTO.FinanceCost financeCost = new ListFinanceRespDTO.FinanceCost();
                financeCost.setYear(year);
                if(baseAll.compareTo(BigDecimal.valueOf(0)) > 0 && base.compareTo(BigDecimal.valueOf(0)) > 0){
                    financeCost.setRate(base.divide(baseAll, Constant.RETAIN_DECIMAL_DIGIT_SIX, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
                costList.add(financeCost);
            
                totalAmount = BigDecimal.valueOf(0);
                baseAll = BigDecimal.valueOf(0);
                base = BigDecimal.valueOf(0);
                year = cash.getYear();
                ++cnt;
                if(cnt >= 5){
                    break;
                }
            }
            ListFinanceRespDTO.FinanceCash financeCash = new ListFinanceRespDTO.FinanceCash();
            financeCash.setYear(cash.getYear());
            financeCash.setEventCode(cash.getEventCode());
            financeCash.setFinancingAmount(cash.getFinancingAmount());
        
            if(null != cash.getFinancingAmount()) {
                totalAmount = totalAmount.add(cash.getFinancingAmount());
            }
            if(null != cash.getBaseAll()) {
                baseAll = baseAll.add(cash.getBaseAll());
            }
            if(null != cash.getBase()) {
                base = base.add(cash.getBase());
            }
        
            cashList.add(financeCash);
        }
        //数据小于5年的时候
        if(list.size() > 0 && cnt < 5){
            for(ListFinanceRespDTO.FinanceCash obj : cashList){
                if(obj.getYear().compareTo(year) == 0 && totalAmount.compareTo(BigDecimal.valueOf(0)) > 0 && null != obj.getFinancingAmount()){
                    obj.setTotalAmount(totalAmount);
                    obj.setRate(obj.getFinancingAmount().divide(totalAmount, Constant.RETAIN_DECIMAL_DIGIT_SIX, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
            }
            //处理融资成本率
            ListFinanceRespDTO.FinanceCost financeCost = new ListFinanceRespDTO.FinanceCost();
            financeCost.setYear(year);
            if(baseAll.compareTo(BigDecimal.valueOf(0)) > 0 && base.compareTo(BigDecimal.valueOf(0)) > 0){
                financeCost.setRate(base.divide(baseAll, Constant.RETAIN_DECIMAL_DIGIT_SIX, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
            }
            costList.add(financeCost);
        }
        //处理空的年份
        if(!year1){
            ListFinanceRespDTO.FinanceCash cash = new ListFinanceRespDTO.FinanceCash();
            cash.setYear(String.valueOf(DateUtils.getYear(new Date())));
            ListFinanceRespDTO.FinanceCost cost = new ListFinanceRespDTO.FinanceCost();
            cost.setYear(String.valueOf(DateUtils.getYear(new Date())));
            
            cashList.add(0,cash);
            costList.add(0,cost);
        }
        if(!year2){
            ListFinanceRespDTO.FinanceCash cash = new ListFinanceRespDTO.FinanceCash();
            cash.setYear(String.valueOf(DateUtils.getYear(new Date()) - 1));
            ListFinanceRespDTO.FinanceCost cost = new ListFinanceRespDTO.FinanceCost();
            cost.setYear(String.valueOf(DateUtils.getYear(new Date()) - 1));
            int curYear = DateUtils.getYear(new Date());
            int idx = 0;
            for(ListFinanceRespDTO.FinanceCash obj : cashList){
                if(curYear > Integer.parseInt(obj.getYear())){
                    break;
                }
                ++idx;
            }
            cashList.add(idx,cash);
            costList.add(1,cost);
        }
        if(!year3){
            ListFinanceRespDTO.FinanceCash cash = new ListFinanceRespDTO.FinanceCash();
            cash.setYear(String.valueOf(DateUtils.getYear(new Date()) - 2));
            ListFinanceRespDTO.FinanceCost cost = new ListFinanceRespDTO.FinanceCost();
            cost.setYear(String.valueOf(DateUtils.getYear(new Date()) - 2));
            int curYear = DateUtils.getYear(new Date()) - 1;
            int idx = 0;
            for(ListFinanceRespDTO.FinanceCash obj : cashList){
                if(curYear > Integer.parseInt(obj.getYear())){
                    break;
                }
                ++idx;
            }
            cashList.add(idx,cash);
            costList.add(2,cost);
        }
        if(!year4){
            ListFinanceRespDTO.FinanceCash cash = new ListFinanceRespDTO.FinanceCash();
            cash.setYear(String.valueOf(DateUtils.getYear(new Date()) - 3));
            ListFinanceRespDTO.FinanceCost cost = new ListFinanceRespDTO.FinanceCost();
            cost.setYear(String.valueOf(DateUtils.getYear(new Date()) - 3));
            int curYear = DateUtils.getYear(new Date()) - 2;
            int idx = 0;
            for(ListFinanceRespDTO.FinanceCash obj : cashList){
                if(curYear > Integer.parseInt(obj.getYear())){
                    break;
                }
                ++idx;
            }
            cashList.add(idx,cash);
            costList.add(3,cost);
        }
        if(!year5){
            ListFinanceRespDTO.FinanceCash cash = new ListFinanceRespDTO.FinanceCash();
            cash.setYear(String.valueOf(DateUtils.getYear(new Date()) - 4));
            ListFinanceRespDTO.FinanceCost cost = new ListFinanceRespDTO.FinanceCost();
            cost.setYear(String.valueOf(DateUtils.getYear(new Date()) - 4));
            int curYear = DateUtils.getYear(new Date()) - 3;
            int idx = 0;
            for(ListFinanceRespDTO.FinanceCash obj : cashList){
                if(curYear > Integer.parseInt(obj.getYear())){
                    break;
                }
                ++idx;
            }
            cashList.add(idx,cash);
            costList.add(4,cost);
        }
        
        resp.setFinanceCashs(cashList);
        resp.setFinanceCosts(costList);
    
        return resp;
    }
    
    @Override
    public PageResult<ListBondFinanceRespVO> listBondFinance(ReqDTO<ListHolderReqVO> req) {
        CompBondFinance compBond = new CompBondFinance();
        BeanUtils.copyProperties(req.getContent(),compBond);
        compBond.setStatus(Constant.DEFAULT_STATUS_NORMAL);
        PageResult<CompBondFinance> page = pageService.page(req.getPageParam(), () -> compBondFinanceService.queryList(compBond));
    
        PageResult<ListBondFinanceRespVO> pageResult = new PageResult<>();
        ListUtil<ListBondFinanceRespVO> listUtil = BeanUtils.instantiateClass(ListUtil.class);
        listUtil.copyList(page,pageResult,ListBondFinanceRespVO.class);
    
        //事件类型名称
        List<ListBondFinanceRespVO> voList = new ArrayList<>();
        Map<String, Dict> dictMap = dictService.queryDict("FINANCE_EVENT");
        if(null != dictMap){
            for(ListBondFinanceRespVO obj:pageResult.getRows()){
                if(!obj.getEventCode().isEmpty() && null != dictMap.get(obj.getEventCode())){
                    obj.setEventName(dictMap.get(obj.getEventCode()).getBusiName());
                }
                voList.add(obj);
            }
        }
        pageResult.setRows(voList);
        
        return pageResult;
    }
    
    @Override
    public PageResult<ListDebitCreditRespVO> listDebitCredit(ReqDTO<ListHolderReqVO> req) {
        CompDebitCredit compDebit = new CompDebitCredit();
        BeanUtils.copyProperties(req.getContent(),compDebit);
        compDebit.setStatus(Constant.DEFAULT_STATUS_NORMAL);
        PageResult<CompDebitCredit> page = pageService.page(req.getPageParam(), () -> compDebitCreditService.queryList(compDebit));
    
        PageResult<ListDebitCreditRespVO> pageResult = new PageResult<>();
        ListUtil<ListDebitCreditRespVO> listUtil = BeanUtils.instantiateClass(ListUtil.class);
        listUtil.copyList(page,pageResult,ListDebitCreditRespVO.class);
        
        return pageResult;
    }
    
    @Override
    public PageResult<ListGuaranteeRespVO> listGuarantee(ReqDTO<ListHolderReqVO> req) {
        CompGuarantee compDebit = new CompGuarantee();
        BeanUtils.copyProperties(req.getContent(),compDebit);
        compDebit.setStatus(Constant.DEFAULT_STATUS_NORMAL);
        PageResult<CompGuarantee> page = pageService.page(req.getPageParam(), () -> compGuaranteeService.queryList(compDebit));
    
        PageResult<ListGuaranteeRespVO> pageResult = new PageResult<>();
        ListUtil<ListGuaranteeRespVO> listUtil = BeanUtils.instantiateClass(ListUtil.class);
        listUtil.copyList(page,pageResult,ListGuaranteeRespVO.class);
        
        return pageResult;
    }
}
